<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />
    <ex_super_table_page v-bind="option" ref="SuperTablePage" @selection-change="e => selection = e"
      @select="selectChange" @search="searchChange">

    </ex_super_table_page>

    <ex_super_dialog_form ref="syncDialog" v-bind="sync_dialog" @afterSubmitSuccess="reload()">
    </ex_super_dialog_form>
    <ex_super_dialog_form ref="uploadFileDialog" v-bind="upload_file_dialog" @afterSubmitSuccess="reload()">
    </ex_super_dialog_form>
  </div>
</template>
<script>
import moment from 'moment-mini-ts'

import superTablePageFunction from '@/mixin/super-table-page-function';
import emitOnFunction from '@/mixin/emit-on-function';

import page_table_model_manage from '@/mixin/page_table_model_manage';
let emitKey = 'platformSync>order_list_wb'

export default {
  title: 'label_wb_order_list',
  mixins: [superTablePageFunction, emitOnFunction(emitKey), page_table_model_manage],
  components: {},
  data() {
    return {
      orderStatus: "WAIT_SUBMIT",
      orderData: {
        waitSubmitCount: null,
        completeSubmitCount: null,
        submitFailCount: null,
        exceptionCount: null,
        canceledCount: null,
      },
      status_map: {
        "WAIT_SUBMIT": 'waitSubmitCount',
        'COMPLETE_SUBMIT': 'completeSubmitCount',
        "SUBMIT_FAIL": 'submitFailCount',
        "EXCEPTION": 'exceptionCount',
        "CANCELED": 'canceledCount',
      },
      selection: [],
      tableData: [],
      option: {
        search: {
          default: { orderStatus: "WAIT_SUBMIT" },
          model: [
            {
              key: 'orderStatus', label: 'label_status', itemClass: "w_fill",
              render: (h, { data }) => {
                let enums = this.$enumOptions['SrmOrderStatusEnum'] || []
                const list = enums.filter(it => !['DRAFT', 'SUBMIT_FAIL', 'EXCEPTION'].includes(it))
                  .map(it => (
                    <el-radio-button key={it} label={it}>
                      {this.$enumShow(it, 'SrmOrderStatusEnum')}
                      {/* {this.status_map[it] && this.orderData[this.status_map[it]] ? `(${this.orderData[this.status_map[it]]})` : "(0)"} */}
                    </el-radio-button>
                  ))
                return (<el-radio-group value={data.orderStatus}
                  onInput={e => {
                    this.orderStatus = e
                    this.$set(data, 'orderStatus', e)
                    this.$refs.SuperTablePage.loadDataForSearch()
                  }}>
                  {/* <el-radio-button key="" label="">
                    {this.$tt("label_all")}
                  </el-radio-button> */}
                  {list}
                </el-radio-group>
                )
              }
            },
            { key: 'platformOrderNo', label: 'label_platform_code', },
            { key: 'supplyId', label: 'label_supply_good_order_code', },
            { key: 'clientId', label: 'label_platform_store', },
            { key: 'trackNumber', label: 'label_track_code', },
            { key: 'omsOrderNo', label: 'label_outbound_code', },


            
            { key: 'validateFlag', label: 'label_verification_pass', type: 'select', enum: "YesOrNoEnum" },

            { key: 'startSyncTime', label: 'label_start_sync_time', type: 'date-picker', attrs: { type: "datetime", 'default-time': '00:00:00' } },
            { key: 'endSyncTime', label: 'label_end_sync_time', type: 'date-picker', attrs: { type: "datetime", 'default-time': '23:59:59' } },
          ],
        },
        action: [
          {
            label: 'label_submit_order', attrs: { type: "primary" },
            if: () => ["", "WAIT_SUBMIT", "SUBMIT_FAIL"].includes(this.orderStatus),

            click: (e) => this.submitOrder(this.selection)
          },
          // {
          //   label: '取消订单',
          //   if: () => ["", "WAIT_SUBMIT", "SUBMIT_FAIL"].includes(this.orderStatus),
          //   attrs: { type: "danger" }, click: (e) => this.cancelOrder(this.selection)
          // },
          {
            label: 'label_retry_check_sku_map',
            if: () => ["", "WAIT_SUBMIT", ].includes(this.orderStatus),
            attrs: { type: "warning" }, click: (e) => this.retryOrder()
          },
          {
            label: "label_sync_order",
            if: () => ["", "WAIT_SUBMIT", ].includes(this.orderStatus),
            click: () => {
              this.$refs.syncDialog.showNew({
                title: this.$tt('label_sync_order'),
                params: {
                  platformCode: "OZON",
                }
              })
            }
          },
          // {
          //   label: "上传交接单",
          //   if: () => ["", "COMPLETE_SUBMIT",].includes(this.orderStatus),

          //   click: () => {
          //     if (_.isEmpty(this.selection)) return this.$message.error(this.$tt('tip_please_select_order'))
          //     this.$refs.uploadFileDialog.showNew({
          //       data: {
          //         postingNumberList: this.selection.map(it => it.postingNumber),
          //       },
          //     })
          //   }
          // },
        ],

        table: {
          url: "/srm-api/ozon/WbClientOrderRpc/selectListPage.json",
          attrs: {
            'cell-class-name': this.cellClassName, 'span-method': this.objectSpanMethod, 'highlight-current-row': false,
            'row-key': 'id',
          },
          urlDataHandle: this.dataHandle,
          model: this.init_table_model(),
        },
      },

      upload_file_dialog: {
        customClass: 'dialog_auto',
        submitUrl: "/srm-api/ozon/WbClientOrderRpc/uploadDeliveryReceiptFile.json",
        submitDataHandle: (data) => {
          return {
            fileName: _.head(data.attachedList).fileName,
            filePath: _.head(data.attachedList).filePath,
            remark: data.remark,
            postingNumberList: data.postingNumberList,
          }
        },
        form: {
          // itemClass: "form_item_default", inputClass: "form_input_default",

          default: {
            attachedList: [], postingNumberList: [],
          },
          model: [
            { header: "label_base_info", },
            {
              key: "tip", label: "label_illustrate", formType: "text",
              formatter: (r, c, v) => this.$tt('tip_xxx_has_select_count_order_upload_handover_order', { count: r.postingNumberList.length })
            },
            {
              key: "remark", label: "label_remark",
            },
            {
              key: 'attachedList', label: 'label_attachment',
              render: (h, { data }) => {
                return h('ex_super_upload', {
                  props: {
                    limit: 1, type: "file", accept: '.pdf',
                    value: data.attachedList
                  },
                  on: {
                    input: (list) => {
                      this.$set(data, 'attachedList', list)
                    }
                  }
                },)
              }
            },


          ],
          rules: {
            'attachedList': { required: true, type: 'array', message: this.$tt('tip_can_no_empty'), },
          },
        }
      },
      sync_dialog: {
        customClass: 'dialog_auto',

        submitUrl: "/srm-api/ozon/WbClientOrderRpc/syncCurrentCustomerWbOrder.json",
        // detailUrl: "/ums-api/client/ThirdPartyAuthorizedClientRpc/selectList.json",
        // detailDataHandle: (data) => {
        //   return {
        //     auths: data.rows
        //   }
        // },
        submitType: 'form',
        submitDataHandle: (data) => {
          return {
            // clientId: data.clientId,
            // apiKey: data.apiKey,
            startTime: data.limitDate[0],
            endTime: data.limitDate[1],
          }
        },
        form: {

          default: {
            auths: [],
          },
          model: [
            { header: "label_base_info", },
            {
              key: "limitDate", label: "label_order_time", type: "date-picker",
              attrs: {
                clearable: false,
                type: 'datetimerange', 'default-time': ['00:00:00', '23:59:59'],
                'picker-options': {
                  shortcuts: this.$date_range_shortcuts(),
                },
              },
            },

          ],
          rules: {
            'limitDate': { required: true, message: this.$tt('tip_can_no_empty'), },


          },
        }
      },
    };
  },
  methods: {
    selectChange(selection, row) {
      const check = selection.includes(row)
      this.$nextTick(() => {
        this.tableData.filter(it => it.supplyId == row.supplyId).forEach(it => {
          this.$refs.SuperTablePage.toggleRowSelection(it, check)
        })
      })


    },
    option_table_model() {
      return [
        { type: 'selection', keyGroup: 'label_table_operate' },
        {
          type: 'expandDesc', 'width': 100,
          expandDesc: {
            ...this.$defaultDescAttrs,
            model: [],
          },
        },
        { key: 'omsOrderNo', label: 'label_outbound_code','width': 140, },
        { key: 'supplyId', label: 'label_supply_good_order_code','width': 140, 'show-overflow-tooltip': true, },
        { key: 'wbId', label: 'label_platform_code', 'width': 140,'show-overflow-tooltip': true, },

        { key: 'clientId', label: 'label_platform_store', 'width': 110, 'show-overflow-tooltip': true, },
        { key: 'trackNumber', label: 'label_track_code', 'width': 110, 'show-overflow-tooltip': true, },
        {
          key: 'orderStatus', label: 'label_status', 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, 'SrmOrderStatusEnum')
        },
        {
          key: 'skus', label: 'label_sku_count', 'width': 110, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => v ? v.split(',').length : 0,
        },
        { key: 'wbWarehouseId', label: 'label_warehouse_id', 'width': 110, 'show-overflow-tooltip': true, },

        { key: 'gmtCreate', label: 'label_sync_time', width: 140, formatter: (r, c, v, i) => this.$dateFormat(v) },


        {
          key: 'cancelTime', label: 'label_cancel_time', if: () => ["CANCELED"].includes(this.orderStatus),
          width: 140, formatter: (r, c, v, i) => this.$dateFormat(v)
        },



        { key: 'validateFlag', label: 'label_verification_pass', 'width': 110, formatter: (r, c, v, i) => this.$enumShow(v, 'YesOrNoEnum') },

        {
          key: 'exceptionMsg', label: 'label_exception_info', 'width': 120,
          render: (h, { row, column }) => {
            const code = row[column.property]
            if (!code) return this.$tt('data_temp_none')
            return (<text_extra_tooltip_operate
              value={code} ellipsis
              data_type={column.property} data_id={row.id}
            />)
          },
        },
        { key: 'createdAt', label: 'label_create_time', 'width': 130, 
        formatter: (r, c, v, i) => moment(v).format('YYYY-MM-DD HH:ss')
        
      },
        {
          type: 'operate', width: 220,
          fixed: 'right',
          operate: [

            { label: 'label_view_detail', click: (row) => this.clickDetail(row) },
            {
              label: 'label_cancel_order',
              disabled: (row) => !['WAIT_SUBMIT', 'SUBMIT_FAIL',].includes(row.orderStatus),
              click: (row) => this.cancelOrder([row])
            },
          ]
        }
      ]
    },
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (['supplyId'].includes(column.property)) {
        if (row.typeIndex % 2 == 0) {
          return 'back_primary_light back_primary_light_hover'
        } else {
          return 'back_warning_light back_warning_light_hover'
        }
        // return 'tableCell_noHoverLight'
      } else if (['validateFlag'].includes(column.property)) {
        if (row.validateFlag == 'N') {
          return 'color_danger'
        } else {
          return 'color_success'
        }
        // return 'tableCell_noHoverLight'
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (['supplyId'].includes(column.property)) {
        // return { rowspan: row.rowspan, colspan: 1 }
      }
    },
    dataHandle(res) {
      const _list = res.data.rows
      _list.sort(it => it.supplyId)
      this.tableData = _list
      let typeIndex = 0
      _.forOwn(_.groupBy(_list, 'supplyId'), (v, k) => {

        v.forEach((it, i) => {
          if (i == 0) {
            this.$set(it, 'rowspan', v.length)
          } else {
            this.$set(it, 'rowspan', 0)
          }
          this.$set(it, 'typeIndex', typeIndex)
        })
        typeIndex++
      })
      return _list
    },
    clickDetail(row) {
      this.$router.push({
        path: '/page/oms/platformSync/sync_order_detail_wb', query: { id: row.id, }
      })
    },
    searchChange() {
      // this.$ajax({
      //   url: this.$url['srm/OzonOrderSyncStatCount'],
      //   method: 'post',
      //   data: this.$refs.SuperTablePage.getSearchFormData(),
      //   success: (res) => {
      //     this.orderData = res.data
      //   }
      // })
    },
    cancelOrder(rows) {
      if (_.isEmpty(rows)) return this.$message.error(this.$tt('tip_please_select_order'))
      if (rows.some(it => !['WAIT_SUBMIT', 'SUBMIT_FAIL'].includes(it.orderStatus))) return this.$message.error(this.$tt('tip_part_order_status_error_no_operate'))

      this.$confirm(this.$tt('tip_confirm_cancel_select_order'), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: "/srm-api/ozon/WbClientOrderRpc/cancelOrder.json",
          method: 'post', type: "json",
          loading: true,
          data: {
            orderIds: rows.map(it => it.id)
          },
          success: (res) => {
            this.$message({
              showClose: true,
              message: this.$tt('tip_submit_success'),
              type: 'success'
            })
            this.reload()
          }
        })
      }).catch(() => {
      });
    },

    submitOrder(rows) {

      if (_.isEmpty(rows)) return this.$message.error(this.$tt('tip_please_select_order'))
      if (rows.some(it => !['WAIT_SUBMIT', 'SUBMIT_FAIL'].includes(it.orderStatus))) return this.$message.error(this.$tt('tip_part_order_status_error_no_operate'))

      const list = _.uniq(rows.map(it => it.supplyId).filter(it => it))
      this.$confirm(this.$tt('tip_xxx_confirm_submit_select_supply_order', { count: list.length }), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: "/srm-api/ozon/WbClientOrderRpc/submitOrder.json",
          method: 'post', type: "json",
          loading: true,
          data: {
            supplyIdList: list
          },
          success: (res) => {
            this.$message({
              showClose: true,
              message: this.$tt('tip_submit_success'),
              type: 'success'
            })
          },
          complete: () => {
            this.reload()

          }
        })
      }).catch(() => {
      });
    },


    retryOrder(rows) {
      // if (_.isEmpty(rows)) return this.$message.error(this.$tt('tip_please_select_order'))
      // if (rows.some(it => !['EXCEPTION'].includes(it.orderStatus))) return this.$message.error(this.$tt('tip_part_order_status_error_no_operate'))

      this.$confirm(this.$tt('tip_confirm_retry_check_sku_map'), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: "/srm-api/ozon/WbClientOrderRpc/retryValidateWbOrder.json",
          method: 'post',
          loading: true,
          data: {
            // orderIds: rows.map(it => it.id)
          },
          success: (res) => {
            this.$message({
              showClose: true,
              message: this.$tt('tip_submit_success'),
              type: 'success'
            })
            this.reload()
          }
        })
      }).catch(() => {
      });
    },
    syncOrder(rows) {
      // if (_.isEmpty(rows)) return this.$message.error(this.$tt('tip_please_select_order'))
      // if (rows.some(it => !['EXCEPTION'].includes(it.orderStatus))) return this.$message.error(this.$tt('tip_part_order_status_error_no_operate'))

      this.$confirm(this.$tt('tip_confirm_sync_order'), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: "/srm-api/ozon/WbClientOrderRpc/syncCurrentCustomerWbOrder.json",
          method: 'post',
          loading: true,
          data: {
            // orderIds: rows.map(it => it.id)
          },
          success: (res) => {
            this.$message({
              showClose: true,
              message: this.$tt('tip_submit_success'),
              type: 'success'
            })
            this.reload()
          }
        })
      }).catch(() => {
      });
    },
  }
};

</script>
<style></style>
